package com.mall.product.exception;

import com.alibaba.fastjson.JSON;
import com.mall.common.exception.HttpStatusCode;
import com.mall.common.exception.ValidationException;
import com.mall.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 谢君臣
 * @Date: 2022/7/21-19:00
 * @version: 1.0
 * @function:
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.mall.product.controller")
public class ControllerException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e){
      log.error("数据校验异常:{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> msg = new HashMap<>();
        if (bindingResult.hasErrors()){
            bindingResult.getFieldErrors().forEach(item->msg.put(item.getField(),item.getDefaultMessage()));
        }
        return new Result().error(HttpStatusCode.VALID_EXCEPTION.getCode(),HttpStatusCode.VALID_EXCEPTION.getMsg(),msg);
    }

    @ExceptionHandler(value = ValidationException.class)
    public Result handleException(ValidationException throwable){
        log.error(throwable.getMessage());
        return new Result().error(throwable.getCode(),throwable.getMessage(),throwable.getData());
    }

    @ExceptionHandler(value = Throwable.class)
    public Result handleException(Throwable throwable){
        log.error(throwable.getMessage());
        return new Result().error(HttpStatusCode.UNDEFINED_EXCEPTION.getCode(),throwable.getMessage());
    }
}
